/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.ipti.br.tag.bo;

import org.ipti.br.tag.dao.WarningFacade;
import org.ipti.br.tag.entity.AbstractEntity;
import org.ipti.br.tag.entity.Warning;
import org.ipti.br.tag.entity.enums.WarningType;
import java.util.List;
import javax.ejb.Stateless;
import javax.inject.Inject;

/**
 *
 * @author luancorumba
 */
@Stateless
public class WarningBO {
    
    @Inject
    private WarningFacade warningFacade;
    
    public void create(WarningType type, AbstractEntity entity, List<AbstractEntity> sons) {
        Warning root;
        if (!exist(type, entity)) {
            root = new Warning(entity, type);
            warningFacade.create(root);
        } else {
            root = warningFacade.findBy(type, entity);
        }
        
        Warning son;
        for (AbstractEntity abstractEntity : sons) {
            if (!exist(type, abstractEntity)) {
                son = new Warning(abstractEntity, type);
                son.setFather(root);
                warningFacade.create(son);
            }
        }
    }
    
    public void resolve(Warning warning) {
        warning.setResolved(true);
        warningFacade.edit(warning);
        if (warning.getFather() != null) {
            boolean all = true;
            for (Warning w : warning.getFather().getSons()) {
                all = (w.isResolved()) ? all : false;
            }
            if (all) {
                warning.getFather().setResolved(true);
                warningFacade.edit(warning.getFather());
            }
        }
    }
    
    public boolean exist(WarningType type, AbstractEntity entity) {
        Warning w = warningFacade.findBy(type, entity);
        return (w != null);
    }
    
    public List<Warning> findRoots() {
        return warningFacade.getRoots();
    }
    
    public List<Warning> findRoots(WarningType type) {
        return warningFacade.getRoots(type);
    }
    
    public List<Warning> findLeafs(WarningType type) {
        return warningFacade.getLeafs(type);
    }
}
